home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18560 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.4 KB  |  55 lines

  1. Path: news.belwue.de!uzwil!kuehl
  2. From: kuehl@uzwil.informatik.uni-konstanz.de (Dietmar Kuehl)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to read: operator overloaded <<
  5. Date: 21 Apr 1996 15:26:03 GMT
  6. Organization: FakultΣt fⁿr Mathematik und Informatik
  7. Message-ID: <4ldk2b$n9o@news.BelWue.DE>
  8. References: <4ldfpc$j0u@amanda.dorsai.org>
  9. Reply-To: dietmar.kuehl@uni-konstanz.de
  10. NNTP-Posting-Host: uzwil.informatik.uni-konstanz.de
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. Jeff Yu (mongoose@dorsai.org) wrote:
  14. : Hi, I have hard time to understand the syntac of << operator overloaded 
  15. : declaration. As it is stated in Lippman's C++ Primer, the << sample is
  16. : supposed to take TWO parameters: ostream& operator<<(ostream& os, String& s)
  17. : But when using it, the way is: cout<<"test"<<MyScreen<<endl;
  18. : Where is the second parameter if I consider the MyScreen as the first one?
  19.  
  20. Operator notation is just a convenience for the programmer. An
  21. expression using operator syntax like this
  22.  
  23.   cout << "test";
  24.  
  25. is converted (logically) by the compiler into an expression which uses
  26. the function call syntax, i.e. on of the following
  27.  
  28.   operator<< (out, str); // non-member function
  29.   cout.operator<< (str); // member function
  30.  
  31. As 'ostream &ostream::operator<< (char const *)' is defined, in the
  32. case of 'char const *' a member function is used for a string literal.
  33. For the class 'String' a non-member function is used. Thus, the
  34. function call notation of your expression looks something like this:
  35.  
  36.   operator << (operator<< (cout.operator<< ("test), MyScreen), endl);
  37.  
  38. Thus, 'MyScreen' becomes the second argument to a call of
  39. 'operator<<()' where the first argument is the value returned from a
  40. call to 'cout.operator<< ("test")'.
  41.  
  42. : What is the difference from ostream& operator << (String &s)?
  43.  
  44. 'operator<< ()' is always a binary operator, thus 'operator << (String
  45. &s)' can only exist as a member function of an appropriate class, i.e.
  46. in the case of the IOStreams library 'ostream'. However, there is no
  47. such function implemented for a class 'String' thus, the only suitable
  48. overload for 'operator <<()' taking a 'String' is as binary, non-member
  49. function (do not try to implement it as a member of a class derived
  50. from 'ostream: It does not work nor is it intended to work).
  51. --
  52. dietmar.kuehl@uni-konstanz.de
  53. http://www.informatik.uni-konstanz.de/~kuehl/
  54. I am a realistic optimist - that's why I appear to be slightly pessimistic
  55.